package test.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author cuichao
 * @Description: NettyClient
 * @Date: create in 2020/12/21 15:00
 */
public class NettyClient {

    public static void main(String[] args) {
        EventLoopGroup executors = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();

        ClientChannel channel = new ClientChannel();


        bootstrap
                .group(executors)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                      /*  ch.pipeline().addLast(new ClientExceptionHandler());*/
                        ch.pipeline().addLast(new ClientDecode());
                        ch.pipeline().addLast(new ClientEncode());
                        ch.pipeline().addLast(channel);
                     /*   ch.pipeline().addLast(new ClientExceptionHandler());*/
                    }
                });

        try {
            ChannelFuture sync = bootstrap.connect("127.0.0.1", 7777).sync();

            System.out.println("Netty客户端启动");

            sync.addListener(future -> {
                if(future.isSuccess()){
                    System.out.println("Netty client was stated");
                }else {
                    System.out.println(future.cause());
                }
            });

            sync.channel().closeFuture().sync();


        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
           executors.shutdownGracefully();
        }


    }

}
